// 定义错误类型
export const ErrorTypes = {
  NETWORK: 'NETWORK_ERROR',
  API: 'API_ERROR',
  LOCATION: 'LOCATION_ERROR',
  UNKNOWN: 'UNKNOWN_ERROR'
}

// 错误信息映射
const ErrorMessages = {
  [ErrorTypes.NETWORK]: '网络连接失败，请检查网络设置',
  [ErrorTypes.API]: 'API调用失败，请稍后重试',
  [ErrorTypes.LOCATION]: '定位失败，请检查定位权限',
  [ErrorTypes.UNKNOWN]: '发生未知错误，请稍后重试'
}

// 统一的错误处理函数
export const handleError = (error, type = ErrorTypes.UNKNOWN) => {
  console.error(`[Error] ${type}:`, error)

  // 显示错误提示
  uni.showToast({
    title: ErrorMessages[type] || ErrorMessages[ErrorTypes.UNKNOWN],
    icon: 'none',
    duration: 3000
  })

  // 可以在这里添加错误上报逻辑
}

// 带重试的异步函数包装器
export const withRetry = async (fn, retryTimes = 3, delay = 1000) => {
  let lastError = null

  for (let i = 0; i < retryTimes; i++) {
    try {
      return await fn()
    } catch (error) {
      lastError = error
      if (i < retryTimes - 1) {
        await new Promise(resolve => setTimeout(resolve, delay))
        
      }
    }
  }

  throw lastError
}